<template>
  <div class="md-select-tree-base" v-loading="loading">
    <el-popover ref="mdSelectTreePopover" placement="bottom" :width="popoverWidth" trigger="click" popper-class="md-select-tree-popover">
      <div class="md-select-tree-data" :style="{'height':height,'overflow-x': 'hidden','overflow-y': 'auto'}">
        <el-tree ref="mdSelectTree" :data="treeData" :node-key="nodeKey" :props="defaultProps" highlight-current @node-click="handleClick">
        </el-tree>
      </div>
      <el-input v-model="label" ref="mdSelectTreeInput" readonly :placeholder="placeholder" slot="reference"></el-input>
    </el-popover>
  </div>
</template>

<script>
export default {
  name: 'MdSelectTreeBaseComponent',
  props: {
    value: [Array, Object, String, Number],
    placeholder: {
      type: String,
      default: '请选择'
    },
    data: {
      type: [Array, Object],
      default: () => {
        return {}
      }
    },
    height: {
      type: String,
      default: '300px'
    },
    nodeKey: {
      type: String,
      default: 'id'
    },
    defaultProps: {
      type: Object,
      default: () => {
        return {
          children: 'children',
          label: 'label'
        }
      }
    },
    /**
     * 是否全部展开
     */
    defaultExpandAll: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      val: null,
      label: null,
      treeData: [],
      popoverWidth: 0,
      loading: false
    }
  },
  watch: {
    data: {
      handler (val) {
        this.treeData = val
      },
      deep: true,
      immediate: true
    },
    value: {
      handler (val) {
        this.val = val
        this.handleSetValue(this.val)
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.popoverWidth = this.$refs.mdSelectTreeInput.$el.offsetWidth
    })
  },
  methods: {
    handleSetValue (val) {
      this.loading = true
      this.$nextTick(() => {
        setTimeout(() => {
          this.$refs.mdSelectTree.setCurrentKey(val)
          const currentNode = this.$refs.mdSelectTree.getCurrentNode()
          if (currentNode) {
            this.label = currentNode[this.defaultProps.label]
          } else {
            this.label = null
          }

          if (this.defaultExpandAll) {
            const nodesMap = this.$refs.mdSelectTree.store.nodesMap
            const keys = Object.keys(nodesMap)
            keys.forEach(key => {
              nodesMap[key].expanded = true
            })
          }
          this.loading = false
        }, 500)
      })
    },
    handleClick (event) {
      this.label = event[this.defaultProps.label]
      this.$emit('input', event[this.nodeKey])
      this.$emit('change', event)
      this.$refs.mdSelectTreePopover.doClose()
    }
  }
}
</script>